<template>
  <div class="takePhoto" v-loading="loading" style="height: 400px;">
    <div class="takePhoto-left" >
      <div class="emptyBox" v-if="istakePhoto == 0">暂无照片</div>
      <video id="video" ref="videos"  v-if="istakePhoto == 1" width="100%" height="400px" autoplay="autoplay"></video>
      <canvas id="canvas" ref="canvas" style="display: none;"  width="500px" height="500px"></canvas>
      <img class="photo"  :src="photo" v-if="istakePhoto == 2" alt="">
    </div>
    <div class="takePhoto-right">
      <div>
        <el-button type="primary" size="medium" plain @click="getMedia">开始采集</el-button>
      </div>
      <div>
        <el-button type="success" :disabled="istakePhoto != 1" size="medium" plain @click="takePhoto">拍照上传</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import qs from "qs"
import { getToken } from "@/utils/auth";
import axios from "axios";
export default {
  props: {
    myPhotoUrl: {
      type: String,
      default() {
        return '';
      }
    },
    istakePhotox: {
      type: Number,
      default() {
        return 0;
      }
    }
  },
  data() {
    return {
      loading: false,
      istakePhoto: 0,

      uploadUrl: "",
      host: "",
      dir: "",
      maxSize: 5,
      headers: {
        Authorization: "Bearer " + getToken()
      },
      data: {},
      imgFile: '',

      photo: '',

      thisVideo: null,

    }
  },
  watch: {
    myPhotoUrl(newVal, oldVal){
      if(newVal == ''){
        this.istakePhoto = 0
        this.photo = ''
      }else{
        this.istakePhoto = 2
        this.photo = newVal
      }


      console.log('ttt', newVal, oldVal)
    },
  },
  mounted(){
    this.getossimg();
    this.photo = this.myPhotoUrl
    this.istakePhoto = this.istakePhotox
    // console.log('vvvvv',this.myPhotoUrl)
    // console.log('------', uuid)
  },
  methods: {
    getMedia(){
      this.istakePhoto = 1
      var _this = this
      this.thisVideo = document.getElementById("video");
      let constraints = {
          video: {width: 500, height: 500},
          audio: true
      };
      //获得video摄像头区域
      // let video = document.getElementById("video");

      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }

      let promise = navigator.mediaDevices.getUserMedia(constraints);
      promise.then(MediaStream => {

        console.log('MediaStream',MediaStream)
          var video = _this.$refs.videos
          _this.thisVideo = MediaStream;
          video.srcObject = MediaStream;
          video.play();

          // 旧的浏览器可能没有srcObject
          // if ("srcObject" in _this.thisVideo) {
          //   _this.thisVideo.srcObject = MediaStream;
          // } else {
          //   // 避免在新的浏览器中使用它，因为它正在被弃用。
          //   _this.thisVideo.src = window.URL.createObjectURL(MediaStream);
          // }
          // _this.thisVideo.onloadedmetadata = function (e) {
          //   _this.thisVideo.play();
          // };
      })
    },
    takePhoto() {

      //获得Canvas对象
      let video = document.getElementById("video");
      // let canvas = document.getElementById("canvas");
      let ctx = this.$refs.canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, 500, 500);
      var image = this.$refs.canvas.toDataURL('image/png')

      var imgFile = this.base64ImgtoFile(image);
      this.imgFile = imgFile
      // console.log("---",image, imgFile)
      this.uploadImg()
    },
    base64ImgtoFile(dataurl, filename = 'file') {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    getossimg() {
      axios
        .get(
          "https://api.mdc.movecloud.cn/api/oss-signature?objname=mcgsCamera"
        )
        .then(res => {
          if (res.status * 1 == 200) {
            this.uploadUrl = res.data.data.host;
            this.data = {
              signature: res.data.data.signature,
              ossAccessKeyId: res.data.data.accessid,
              policy: res.data.data.policy,
              key: res.data.data.dir + res.data.sys_time
            };
            this.host = res.data.data.host;
            this.dir = res.data.data.dir + res.data.sys_time;


          }
        });
    },
    uploadImg(){
      var _this = this
      this.loading = true
      var data = this.data
      var uuid = this.guid()
      var nkey = data.key+'/'+ uuid +'.png'
      let param = new FormData()  // 创建form对象
      param.append('signature', data.signature)  // 通过append向form对象添加数据
      param.append('ossAccessKeyId', data.ossAccessKeyId)  // 通过append向form对象添加数据
      param.append('policy', data.policy)  // 通过append向form对象添加数据
      param.append('key', nkey)  // 通过append向form对象添加数据
      param.append('file', this.imgFile)  // 通过append向form对象添加数据
      // data.file = this.imgFile
      axios
        .post(this.host, param, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': "Bearer " + getToken()
          }
        })
        .then(res => {
          this.loading = false
          this.photo = this.host+'/'+nkey
          this.istakePhoto = 2

          // var video = _this.$refs.videos
          // this.thisVideo.srcObject = MediaStream;
          // video.srcObject = MediaStream;
          // video.play();
          this.thisVideo.getVideoTracks().forEach(function (track) {
            track.stop();
          });
          // this.thisVideo.getTracks()[0].stop();
          console.log('===111')
          this.$emit('getPhotoUrl', this.photo)
        });
    },
    S4() {
      return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    },
    guid() {
      return (this.S4()+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+this.S4()+this.S4());
    }


  },
}
</script>

<style lang="less" scoped>
.takePhoto{
  width: 50%;
  // height: 400px;
  // background: red;
  margin-left: 20px;
  display: flex;
  border: 1px solid #eee;
  .takePhoto-left{
    width: 60%;
    height: 100%;
    background: #f9f9f9;
  }
  .takePhoto-right{
    // display: block;
    text-align: center;
    flex-grow: 1;
    display: flex;
    // display: flex;
    flex-wrap: wrap;
    align-items: center;
    div{
      width: 100%;
      text-align: center;
      .el-button{

      }
    }

  }
}

.emptyBox{
  text-align: center;
  color: #999;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.photo{
  width: 100%;
  // height: 400px;
}
</style>
